package com.wl.cloud.core.lang;

import cn.hutool.core.map.MapUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * @author: wanglin
 * @date: 2023-09-22 周五
 * @Version: 1.0
 * @Description: 安全的ConcurrentHashMap实现 此类用于解决在JDK8中调用ConcurrentHashMap.computeIfAbsent(Object, Function)可能造成的死循环问题
 */
public class CustomSafeConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {
    private static final long serialVersionUID = 1L;

    /**
     * 构造，默认初始大小（16）
     */
    public CustomSafeConcurrentHashMap() {
        super();
    }

    /**
     * 构造
     *
     * @param initialCapacity 预估初始大小
     */
    public CustomSafeConcurrentHashMap(int initialCapacity) {
        super(initialCapacity);
    }

    /**
     * 构造
     *
     * @param m 初始键值对
     */
    public CustomSafeConcurrentHashMap(Map<? extends K, ? extends V> m) {
        super(m);
    }

    /**
     * 构造
     *
     * @param initialCapacity 初始容量
     * @param loadFactor      增长系数
     */
    public CustomSafeConcurrentHashMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }

    /**
     * 构造
     *
     * @param initialCapacity  初始容量
     * @param loadFactor       增长系数
     * @param concurrencyLevel 并发级别，即Segment的个数
     */
    public CustomSafeConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
        super(initialCapacity, loadFactor, concurrencyLevel);
    }
    // endregion == 构造 ==

    @Override
    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        return MapUtil.computeIfAbsent(this, key, mappingFunction);
    }
}
